Page({
  data:{
    type:'',
    list:[],
    currentIndex:0,
    currentIndexDisplay:1,
    current:{},
    total:0,
    hasPrev:false,
    hasNext:false,
    unprocessedCount:0,
    pageTitle:'消息详情',
    statusText:''
  },
  onLoad(options){
    const type=options.type||'message'
    const payload=wx.getStorageSync('home_detail_payload')||{}
    const list=(payload.list||[]).map(item=>({ ...item }))
    let idx=0
    const ci=payload.currentIndex
    if(typeof ci==='number'){
      idx=ci
    }else if(ci && typeof ci==='object'){
      if(typeof ci.index==='number') idx=ci.index
      else if(typeof ci.id==='number'){
        const found=list.findIndex(x=>x.id===ci.id)
        idx=found>=0?found:0
      }else{
        idx=0
      }
    }
    if(idx<0) idx=0
    if(idx>=list.length) idx=Math.max(0,list.length-1)
    this.setData({ type, list, currentIndex: idx, total: list.length })
    this.updateCurrent()
  },
  updateCurrent(){
    const {list,currentIndex}=this.data
    const cur=list[currentIndex]||{}
    const statusText=this.mapStatus(cur.status)
    const unprocessed=list.filter(i=>i.status==='unread'||i.status==='urgent'||i.status==='important').length
    this.setData({ current:cur, statusText, unprocessedCount: unprocessed, hasPrev: currentIndex>0, hasNext: currentIndex<list.length-1, pageTitle:`${this.mapType(this.data.type)}详情`, currentIndexDisplay: (list.length? (currentIndex+1):0) })
  },
  mapType(t){
    switch(t){
      case 'project': return '项目消息'
      case 'todo': return '待办事项'
      case 'warning': return '预警信息'
      case 'daily': return '工作日报'
      default: return '我的消息'
    }
  },
  mapStatus(s){
    switch(s){
      case 'unread': return '未读'
      case 'read': return '已读'
      case 'urgent': return '紧急'
      case 'important': return '重要'
      default: return '—'
    }
  },
  onPrev(){ if(!this.data.hasPrev) return; const ni=this.data.currentIndex-1; this.setData({ currentIndex: ni<0?0:ni }); this.updateCurrent() },
  onNext(){ if(!this.data.hasNext) return; const ni=this.data.currentIndex+1; const max=this.data.list.length-1; this.setData({ currentIndex: ni>max?max:ni }); this.updateCurrent() },
  onMarkUnread(){
    const list=[...this.data.list];
    if(!list.length) return wx.showToast({title:'无数据',icon:'none'})
    const idx=this.data.currentIndex
    if(!list[idx]) return wx.showToast({title:'索引错误',icon:'none'})
    list[idx].status='unread'
    this.setData({list});
    this.updateCurrent()
    wx.showToast({title:'已标记未读',icon:'success'})
  },
  onMarkProcessed(){
    const list=[...this.data.list];
    if(!list.length) return wx.showToast({title:'无数据',icon:'none'})
    const idx=this.data.currentIndex
    if(!list[idx]) return wx.showToast({title:'索引错误',icon:'none'})
    list[idx].status='read'
    this.setData({list});
    this.updateCurrent()
    wx.showToast({title:'已标记已处理',icon:'success'})
  }
})
